<?php
/**
 * 数据库初始化类
 */

namespace style\lib;

use style\lib\db\Connection;

class moder
{
  private $db;
  public $service = '';

  function __construct($service)
  {
    $this->service = $service;
  }

  function get()
  {
    //性能考虑确保在一个方法里面只有一次初始化设置
    if ($this->db) {
      $this->service->db = $this->db;
      return $this->db;
    } else {
      try {
        $confg = \app\confg\db::get();
        $this->db = new Connection($confg['dsn'], $confg['username'], $confg['password'], $confg['option'], $confg['charset'], $confg['tablePrefix']);
        $this->db->open();
      } catch (\Exception $e) {
        throw new \Exception('数据库连接错误' . $e->getMessage() . PHP_EOL);
      }
      $this->service->db = $this->db;
      return $this->db;
    }
  }

  /**
   * 发送sql语法来保持连接防止掉线
   */
  function db_task()
  {
    try {
      $this->db->createCommand("show full processlist")->queryOne();
      return;
    } catch (\Exception $e) {
      throw new \Exception('重新连接mysql失败' . $e->getMessage());
    }
  }


}